package backend.Instruction;

import backend.Register.RISCVoperand;
import backend.Register.virtualFReg;

import java.util.ArrayList;
import java.util.List;

public class RISCVstore extends RISCVinst {
    private String type;
    private List<RISCVoperand> operands = new ArrayList<>();

    public String type() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public RISCVstore(List<RISCVoperand> operands, String type) {
        this.operands = operands;
        setSrc(operands.get(0));
        setAddress(operands.get(1));
        setOffset(operands.get(2));
        //第一个是 dest 第二个是 oprand
        this.type = type;
    }

    public void setSrc(RISCVoperand src) {
        addUseReg(operands.get(0), src);
        operands.set(0, src);
    }

    public void setAddress(RISCVoperand address) {
        addUseReg(operands.get(1), address);
        operands.set(1, address);
    }

    public void setOffset(RISCVoperand offset) {
        addUseReg(operands.get(2), offset);
        operands.set(2, offset);
    }

    public RISCVoperand getAddress() {
        return operands.get(1);
    }

    public RISCVoperand getOffset() {
        return operands.get(2);
    }

    public RISCVoperand getSrc() {
        return operands.get(0);
    }

    @Override
    public void replaceReg(RISCVoperand oldReg, RISCVoperand newReg) {
        if (operands.get(0).equals(oldReg)) {
            setSrc(newReg);
        }
        if (operands.get(1).equals(oldReg)) {
            setAddress(newReg);
        }
        if (operands.get(2).equals(oldReg)) {
            setOffset(newReg);
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(type).append(" ").append(operands.get(0))
                .append(", ").append(operands.get(2))
                .append("(").append(operands.get(1)).append(")");
        if (operands.get(0) instanceof virtualFReg) {
            sb.insert(0, "f");
        }
        sb.append("\n");
        return sb.toString();
    }
}
